#pragma once
#include <iostream>
#include <pthread.h>
#include <string>
#include <queue>
#include <vector>
#include <unistd.h>


struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};


static const int defaultnum =5;

template<class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&cond_,&mutex_);
    }
    bool IsQueueEmpty()
    {
        return tasks_.empty();
    }
    T pop()
    {
        T t =tasks_.front();
        tasks_.pop();
        return t;
    }
public:
    ThreadPool(int num =defaultnum)
        :threads_(num)//-------------????????????????????????????
    {
        pthread_mutex_init(&mutex_,nullptr);
        pthread_cond_init(&cond_,nullptr);
    }

    static void* HandlerTask(void* args)
    {
        ThreadPool<T> *tp =static_cast<ThreadPool*>(args);
        while(true)
        {
            tp->Lock();
            while(tp->IsQueueEmpty())
            {
                tp->ThreadSleep();
            }
            T t=tp->pop();
            tp->Unlock();
            //执行任务
            cout<<"执行任务中...."<<endl;
        }
    }

    void Start()
    {
        int num=threads_.size();
        for(int i=0;i<num;i++)
        {
            threads_[i].name="thread-"+std::to_string(i+1);
            pthread_create(&(threads_[i].tid),nullptr,HandlerTask,this);
        }
    }

    void Push(const T& t)//-----生产一个任务,从外部获取
    {
        Lock();
        tasks_.push(t);
        wakeup();//唤醒进程去执行任务
        Unlock();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

private:
    std::vector<ThreadInfo> threads_;
    std::queue<T> tasks_;

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};